// 导入CSS文件
import '../css/func1.css';
// 导入axios库
import axios from 'axios';

// API配置 - 匹配后端地址
const API_CONFIG = {
  SIMILAR_STUDENTS_API: 'http://localhost:8080/api/v1/students/temp-similar',
  EXPORT_STUDENTS_API: 'http://localhost:8080/api/v1/students/export',
};

// 开启调试日志（便于查看数据流转）
const DEBUG_MODE = true;

// 工具函数：日志记录
function log(message, level = 'info') {
  if (DEBUG_MODE) {
    const timestamp = new Date().toISOString();
    console[level === 'error' ? 'error' : 'log'](`[${timestamp}] [${level}] ${message}`);
  }
};

// 工具函数：生成随机token
function generateToken() {
  const timestamp = Date.now();
  const randomStr = Math.random().toString(36).substring(2, 10);
  return `token_${timestamp}_${randomStr}`;
}

document.addEventListener('DOMContentLoaded', function () {
  // 底部按钮事件（保留原逻辑）
  const backToMainBtn = document.getElementById('backToMainBtn');
  const toPredictBtn = document.getElementById('toPredictBtn');
  const toFunc2Btn = document.getElementById('toFunc2Btn');
  if (backToMainBtn) backToMainBtn.addEventListener('click', () => window.location.href = '/main.html');
  if (toPredictBtn) toPredictBtn.addEventListener('click', () => window.location.href = '/predict.html');
  if (toFunc2Btn) toFunc2Btn.addEventListener('click', () => window.location.href = '/func2.html');

  // 个人信息显示元素
  const majorDisplay = document.getElementById('majorDisplay');
  const collegeDisplay = document.getElementById('collegeDisplay');
  const targetSchoolDisplay = document.getElementById('targetSchoolDisplay');

  // 初始化流程
  displayUserInfo(); // 显示用户信息
  const userScores = JSON.parse(localStorage.getItem('userScores') || '{}');
  updateScoreTable(userScores); // 更新成绩表格
  fetchSimilarStudents(); // 核心：获取并渲染相似学生

  // 导出按钮事件
  const saveStudentsBtn = document.getElementById('saveStudentsBtn');
  if (saveStudentsBtn) saveStudentsBtn.addEventListener('click', exportStudentsToExcel);


  // -------------------------- 核心修改1：修正localStorage字段名（避免信息显示“未设置”） --------------------------
  function displayUserInfo() {
    const Major = localStorage.getItem('userMajor') || '未设置';
    // 修正：Usercollege → userCollege（与input.js保存的key完全对齐）
    const college = localStorage.getItem('userCollege') || '未设置';
    const TargetSchool = localStorage.getItem('userTargetSchool') || '未设置';

    if (majorDisplay) majorDisplay.textContent = Major;
    if (collegeDisplay) collegeDisplay.textContent = college;
    if (targetSchoolDisplay) targetSchoolDisplay.textContent = TargetSchool;
    log(`用户信息：专业=${Major}，学院=${college}，目标院校=${TargetSchool}`);
  }


  // -------------------------- 保留原逻辑：更新用户成绩表格 --------------------------
  function updateScoreTable(userScores) {
    if (!userScores) return;
    const gpaValue = document.getElementById('gpaValue');
    const cet4Value = document.getElementById('cet4Value');
    const math1Value = document.getElementById('math1Value');
    const math2Value = document.getElementById('math2Value');
    const english1Value = document.getElementById('english1Value');
    const english2Value = document.getElementById('english2Value');
    const english3Value = document.getElementById('english3Value');
    const english4Value = document.getElementById('english4Value');

    if (gpaValue) gpaValue.textContent = userScores.gpa || 0;
    if (cet4Value) cet4Value.textContent = userScores.cet4 || 0;
    if (math1Value) math1Value.textContent = userScores.math1 || 0;
    if (math2Value) math2Value.textContent = userScores.math2 || 0;
    if (english1Value) english1Value.textContent = userScores.english1 || 0;
    if (english2Value) english2Value.textContent = userScores.english2 || 0;
    if (english3Value) english3Value.textContent = userScores.english3 || 0;
    if (english4Value) english4Value.textContent = userScores.english4 || 0;
  }


  // -------------------------- 核心修改2：提取后端嵌套的学生数组（response.data.data） --------------------------
  function fetchSimilarStudents() {
    try {
      // 读取用户信息（修正college字段名）
      const userScores = JSON.parse(localStorage.getItem('userScores') || '{}');
      const Major = localStorage.getItem('userMajor') || '';
      const college = localStorage.getItem('userCollege') || '';
      const TargetSchool = localStorage.getItem('userTargetSchool') || '';

      const requestData = {
        ...userScores,
        Major: Major,
        college: college,
        TargetSchool: TargetSchool,
        token: generateToken()
      };

      log('发送相似学生请求，参数:', requestData);

      axios.post(API_CONFIG.SIMILAR_STUDENTS_API, requestData, {
        headers: { 'Content-Type': 'application/json' }
      })
        .then(response => {
          log('后端原始返回数据:', response.data);
          
          // 关键：从后端返回的data字段中提取学生数组（匹配你提供的JSON结构）
          const similarStudents = response.data.data || [];
          log(`提取到相似学生数量: ${similarStudents.length}`, 'info');
          
          
          // 调用渲染函数
          displaySimilarStudents(similarStudents);
        })
        .catch(error => {
          log('获取相似学生失败:', error, 'error');
          alert('获取相似学生信息失败，请查看控制台日志');
        });
    } catch (error) {
      log('获取相似学生过程出错:', error, 'error');
      alert('获取相似学生信息失败，请查看控制台日志');
    }
  }


  // -------------------------- 核心修改3：匹配后端字段，完整渲染学生信息 --------------------------
  function displaySimilarStudents(students) {
    // 1. 验证学生数组有效性
    if (!Array.isArray(students) || students.length === 0) {
      alert('未找到相似学生信息');
      log('学生数据无效：非数组或空数组', 'warning');
      return;
    }

    // 2. 确保渲染容器存在（页面没有则自动创建）
    let studentContainer = document.getElementById('studentContainer');
    if (!studentContainer) {
      log('页面无studentContainer，自动创建渲染容器', 'info');
      // 创建容器并添加基础样式（保证排版美观）
      studentContainer = document.createElement('div');
      studentContainer.id = 'studentContainer';
      studentContainer.style.cssText = `
        margin: 2rem 0;
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 1.5rem;
        padding: 0 1rem;
      `;
      // 插入到成绩表格后面（或body末尾）
      const scoreTable = document.querySelector('.score-table');
      if (scoreTable) scoreTable.after(studentContainer);
      else document.body.appendChild(studentContainer);
    }

    // 3. 清空旧内容，渲染新学生卡片（字段完全匹配后端返回）
    studentContainer.innerHTML = '';
    // 限制最多显示10个学生卡片
    const displayStudents = students.slice(0, 10);
    displayStudents.forEach((student, index) => {
      // 创建学生卡片
      const studentCard = document.createElement('div');
      studentCard.className = 'student-card';
      // 卡片基础样式（可在func1.css中扩展）
      studentCard.style.cssText = `
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        padding: 1.2rem;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        background: #fff;
      `;

      // 卡片内容：完全匹配后端字段（id、name、gpa、savedMajor等）
      studentCard.innerHTML = `
        <div style="font-size: 1.1rem; font-weight: 600; color: #1976d2; margin-bottom: 0.8rem;">
          相似学生 ${index + 1}
        </div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>GPA：</strong>${student.gpa || 0}</div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>CET4：</strong>${student.cet4 || 0}</div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>数学1：</strong>${student.math1 || 0}</div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>数学2：</strong>${student.math2 || 0}</div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>英语1：</strong>${student.english1 || 0}</div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>英语2：</strong>${student.english2 || 0}</div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>英语3：</strong>${student.english3 || 0}</div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>英语4：</strong>${student.english4 || 0}</div>
        <div style="line-height: 1.6; margin-bottom: 0.5rem;"><strong>原专业：</strong>${student.savedMajor || '未提供'}</div>
        <div style="line-height: 1.6;"><strong>录取院校：</strong>${student.savedCollege || '未提供'}</div>
      `;

      studentContainer.appendChild(studentCard);
    });

    log(`成功渲染 ${students.length} 个相似学生卡片`, 'info');
  }


  // -------------------------- 修正导出功能的localStorage字段名 --------------------------
  function exportStudentsToExcel() {
    try {
      const userScores = JSON.parse(localStorage.getItem('userScores') || '{}');
      const Major = localStorage.getItem('userMajor') || '';
      const college = localStorage.getItem('userCollege') || ''; // 修正字段名
      const TargetSchool = localStorage.getItem('userTargetSchool') || '';

      const requestData = {
        ...userScores,
        Major: Major,
        college: college,
        TargetSchool: TargetSchool,
        student_id: generateStudentId()
      };

      log('发送导出请求，参数:', requestData);

      axios.post(API_CONFIG.EXPORT_STUDENTS_API, requestData, {
        headers: { 'Content-Type': 'application/json' },
        responseType: 'blob'
      })
        .then(response => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', 'similar_students_info.xlsx');
          document.body.appendChild(link);
          link.click();
          link.parentNode.removeChild(link);
          window.URL.revokeObjectURL(url);
          alert('相似学生信息已成功导出！');
        })
        .catch(error => {
          log('导出失败:', error, 'error');
          alert('导出学生信息失败，请查看控制台日志');
        });
    } catch (error) {
      log('导出过程出错:', error, 'error');
      alert('导出学生信息失败，请查看控制台日志');
    }
  }
});